using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;

namespace HyperbolaControl
{
    public partial class MainForm : Form
    {
        private readonly string[] dataNames = new string[80];
        private readonly string[] dataUnits = new string[80];
        private readonly HyperbolaControl[] hyperbolaControls = new HyperbolaControl[8];
        private readonly Timer dataTimer = new Timer();
        private readonly Timer displayTimer = new Timer();
        private readonly Random random = new Random();
        private readonly List<float>[] dataCache = new List<float>[80];
        private float[] currentData = new float[80];
        private System.Threading.Timer saveTimer;
        private readonly NumericDisplayControl[,] numericDisplays = new NumericDisplayControl[2, 8];
        private int NowPageIndex = 0;

        public MainForm()
        {
            this.Text = "能耗检测系统";
            this.Size = new System.Drawing.Size(800, 600);

            InitializeControls();

            for (int i = 0; i < 80; i++)
            {
                dataCache[i] = new List<float>();
            }

            // 数据生成定时器 - 一次性生成80个数据
            dataTimer = new Timer();
            dataTimer.Interval = 1000; // 1秒生成一次
            dataTimer.Tick += DataTimer_Tick;
            dataTimer.Start();

            // 数据显示定时器 - 以更快的频率更新界面
            displayTimer = new Timer();
            displayTimer.Interval = 1000; // 100ms更新一次
            displayTimer.Tick += DisplayTimer_Tick;
            displayTimer.Start();

            // 数据保存定时器
            saveTimer = new System.Threading.Timer(SaveDataToFile, null, 1000, 1000);
        }

        private void InitializeControls()
        {
            // 读取并缓存config.xml文件数据
            var doc = new System.Xml.XmlDocument();
            doc.Load("config.xml");
            var nodes = doc.SelectNodes("/DataConfig/DataItems/DataItem");

            for (int i = 0; i < 80; i++)
            {
                if (nodes != null && i < nodes.Count)
                {
                    var node = nodes[i];
                    dataNames[i] = node.Attributes["Name"]?.Value ?? $"参数{i + 1}";
                    dataUnits[i] = node.Attributes["Unit"]?.Value ?? "单位";
                }
                else
                {
                    dataNames[i] = $"参数{i + 1}";
                    dataUnits[i] = "单位";
                }
            }

            // Top panel with numeric displays
            var topPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Top,
                Height = 150,
                ColumnCount = 8,
                RowCount = 2,
                CellBorderStyle = TableLayoutPanelCellBorderStyle.None,
                Margin = new Padding(0),
                Padding = new Padding(0)
            };

            for (int row = 0; row < 2; row++)
            {
                for (int col = 0; col < 8; col++)
                {
                    int index = row * 8 + col;

                    numericDisplays[row, col] = new NumericDisplayControl
                    {
                        Dock = DockStyle.Fill,
                        DisplayName = dataNames[index],
                        Unit = dataUnits[index],
                        Value = 0,
                        Margin = new Padding(1)
                    };

                    // 设置数值颜色
                    if (row == 0)
                        numericDisplays[row, col].ValueColor = Color.Lime; // 第一行亮绿色
                    else
                        numericDisplays[row, col].ValueColor = Color.Cyan; // 第二行天蓝色
                    topPanel.Controls.Add(numericDisplays[row, col], col, row);
                    topPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 12.5f));
                }
                topPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 50f));
            }

            // 添加按钮面板
            var buttonPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Bottom,
                Height = (int)(this.Height * 0.1), // 10%高度
                ColumnCount = 7,
                RowCount = 1,
                CellBorderStyle = TableLayoutPanelCellBorderStyle.None,
                Margin = new Padding(0),
                Padding = new Padding(0)
            };

            // 添加7个按钮
            string[] buttonTexts = { "第1页", "第2页", "第3页", "第4页", "第5页", "刷新（暂停）", "主菜单" };
            for (int i = 0; i < 7; i++)
            {
                var button = new Button
                {
                    Text = buttonTexts[i],
                    Dock = DockStyle.Fill,
                    Margin = new Padding(2)
                };
                button.FlatStyle = FlatStyle.Flat;
                button.BackColor = Color.DarkBlue;
                button.ForeColor = Color.White;
                button.Font = new Font("微软雅黑", 12, FontStyle.Bold);
                button.FlatAppearance.BorderSize = 0;
                button.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 0, 100);

                if (i < 5) // Page buttons
                {
                    NowPageIndex = i + 1;
                    button.Click += (sender, e) => ShowPage(NowPageIndex);
                }
                else if (i == 5) // Refresh/Pause button
                {
                    button.Click += (sender, e) => ToggleRefresh();
                }
                else // Main menu button
                {
                    button.Click += (sender, e) => ShowMainMenu();
                }

                buttonPanel.Controls.Add(button, i, 0);
                buttonPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / 7));
            }

            // Middle panel with 8 curve controls in 1x8 grid
            var middlePanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 8,
                RowCount = 1,
                CellBorderStyle = TableLayoutPanelCellBorderStyle.None,
                Margin = new Padding(0),
                Padding = new Padding(0)
            };

            for (int i = 0; i < 8; i++)
            {
                hyperbolaControls[i] = new HyperbolaControl { Dock = DockStyle.Fill, Margin = new Padding(1) };
                middlePanel.Controls.Add(hyperbolaControls[i], i, 0);
                middlePanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 12.5f));
            }
            middlePanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100f));

            // Add panels to main form
            this.Controls.Add(topPanel);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(middlePanel);
            topPanel.BringToFront();
            buttonPanel.BringToFront();
            middlePanel.BringToFront();
        }

        private void ShowPage(int pageNum)
        {
            int startIndex = (pageNum - 1) * 16;
            int endIndex = Math.Min(startIndex + 15, 79);

            // Update numeric displays
            for (int i = 0; i < 16; i++)
            {
                int dataIndex = startIndex + i;
                if (dataIndex <= endIndex)
                {
                    // Update corresponding numeric display
                    int row = i / 8;
                    int col = i % 8;
                    numericDisplays[row, col].Value = (float)(random.NextDouble() * 100);

                    // Update name and unit from cached data
                    numericDisplays[row, col].DisplayName = dataNames[dataIndex];
                    numericDisplays[row, col].Unit = dataUnits[dataIndex];
                }
            }

            // Update curve controls
            for (int i = 0; i < 8; i++)
            {
                hyperbolaControls[i].Curve1Values.Clear();
                hyperbolaControls[i].Curve2Values.Clear();

                for (int j = 0; j < 10; j++)
                {
                    hyperbolaControls[i].Curve1Values.Add((float)(random.NextDouble() * 100));
                    hyperbolaControls[i].Curve2Values.Add((float)(random.NextDouble() * 100));
                }
                hyperbolaControls[i].Invalidate();
            }
        }

        private void ToggleRefresh()
        {
            dataTimer.Enabled = !dataTimer.Enabled;
        }

        private void ShowMainMenu()
        {
            // Implement main menu display logic
        }

        private void DataTimer_Tick(object sender, EventArgs e)
        {
            // 一次性生成80个数据
            for (int i = 0; i < 80; i++)
            {
                currentData[i] = (float)(random.NextDouble() * 100);
                dataCache[i].Add(currentData[i]);
                if (dataCache[i].Count > 100) // 限制缓存大小
                    dataCache[i].RemoveAt(0);
            }
        }

        private void DisplayTimer_Tick(object sender, EventArgs e)
        {
            // 更新数值显示控件
            for (int i = 0; i < 16; i++) // 只显示当前页面的16个数值
            {
                int row = i / 8;
                int col = i % 8;
                int index = (NowPageIndex - 1) * 16 + i;
                if (numericDisplays[row, col] != null)
                    numericDisplays[row, col].Value = currentData[index];
            }

            // 更新曲线控件
            for (int i = 0; i < 8; i++)
            {
                if (hyperbolaControls[i] != null)
                {
                    hyperbolaControls[i].UpdateData(dataCache[i * 2].ToArray(), dataCache[i * 2 + 1].ToArray());
                }
            }
        }

        private void SaveDataToFile(object state)
        {
            bool hasData = false;
            for (int i = 0; i < 80; i++)
            {
                if (dataCache[i].Count > 0)
                {
                    hasData = true;
                    break;
                }
            }
            if (!hasData) return;

            string fileName = DateTime.Now.ToString("yyyyMMdd_HH") + ".csv";
            string currentTime = DateTime.Now.ToString("HH:mm:ss");

            using (var writer = new System.IO.StreamWriter(fileName, true))
            {
                string line = currentTime;
                for (int i = 0; i < 80; i++)
                {
                    if (dataCache[i].Count > 0)
                    {
                        line += $",{dataCache[i][0]}";
                        dataCache[i].RemoveAt(0);
                    }
                    else
                    {
                        line += ",0";
                    }
                }
                writer.WriteLine(line);
            }

            for (int i = 0; i < 80; i++)
            {
                dataCache[i].Clear();
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}